package com.llap.exp190929.controller;

import com.llap.exp190929.dto.PaginatedDto;
import com.llap.exp190929.entity.Invitation;
import com.llap.exp190929.entity.User;
import com.llap.exp190929.error.RestException;
import com.llap.exp190929.error.UnauthorizedException;
import com.llap.exp190929.security.JwtUser;
import com.llap.exp190929.service.InvitationService;
import com.llap.exp190929.util.Util;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * Created by LLAP on 2019/10/14.
 * Copyright (c) 2019 LLAP. All rights reserved.
 */
@RestController
@RequestMapping("invitations")
@AllArgsConstructor
@CrossOrigin
@Slf4j
public class InvitationsController {
    private InvitationService invitationService;

    @GetMapping("")
    public PaginatedDto<Invitation> findInvitations(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {
        return PaginatedDto.from(invitationService.findInvitations(page, pageSize));
    }

    @GetMapping("{id}")
    public Invitation findInvitation(@PathVariable Integer id) {
        return invitationService.findInvitation(id);
    }

    @PostMapping("")
    public Invitation addInvitation(@RequestBody Invitation invitation) throws RestException {
        User user = User.from(Util.getLoginUser());
        if (user == null) throw new UnauthorizedException("");
        invitation.setAuthor(user);
        return invitationService.addInvitation(invitation);
    }

    @DeleteMapping("")
    public void deleteInvitation(@RequestParam Integer id) {
        invitationService.deleteInvitation(id);
    }

    @PatchMapping("")
    public Invitation updateInvitation(@RequestBody Invitation invitation) {
        return invitationService.updateInvitation(invitation);
    }
}
